from umqtt.simple import MQTTClient
import time
from machine import Timer
import machine
from machine import SoftI2C, Pin,PWM
from oled import OLED12864_I2C
import dht
import neopixel
import json
import time

#为micropython esp32主板编写



# import threading
# 假设的阈值
# THRESHOLD = 3000
sub_number=3000
# 用于存储接收到的值
# received_value = None
# # 手动赋值标志，用于标记是否有待处理的手动赋值
# manual_assignment_pending = False
# def timer_function():
#     global received_value, manual_assignment_pending
#     while True:
#         # 等待两秒
#         time.sleep(2)
#
#         # 检查是否有待处理的手动赋值
#         if manual_assignment_pending:
#             # 处理手动赋值，并清除标志
#             process_manual_assignment()
#             manual_assignment_pending = False
#         else:
#             # 没有手动赋值，检查自动接收的值
#             if received_value is not None and abs(received_value) < THRESHOLD:
#                 # 如果自动接收的值未达到阈值，则处理它
#                 process_automatic_reception(received_value)
#                 received_value = None  # 重置值，以便下次接收


fengshan_pin1 = Pin(2,Pin.OUT) #风扇
fengshan_pin2 = Pin(4,Pin.OUT)
fengshan_message = "OFF"

shuibeng_pin1 = Pin(13,Pin.OUT) #水泵
shuibeng_pin2 = Pin(27,Pin.OUT)
shuibeng_message = "OFF"

Key = Pin(18,Pin.IN) #开关


beeper = PWM(Pin(5))   #蜂鸣器
button_c = Pin(19,Pin.IN)
beeper_message = "OFF"
# if beeper_message == "OFF":
#     beeper.duty(0)
#     beeper.deinit()
# elif beeper_message == "ON":
#     beeper.init(duty=1000, frep=263)


dht = dht.DHT11(Pin(32)) #湿度传感器

i2c = SoftI2C(scl=Pin(22), sda=Pin(21)) #oled屏幕
oled = OLED12864_I2C(i2c)


soil_sensor = machine.ADC(Pin(35))   #土壤传感器
water_sensor = machine.ADC(Pin(39))   #水位传感器
light_sensor = machine.ADC(Pin(36))   #光敏传感器
rain_sensor = machine.ADC(Pin(34))       #雨滴传感器  （正常是17,34针脚）

rgb_pin16 = Pin(16, Pin.OUT)          #主板上的lgb灯
rgb = neopixel.NeoPixel(rgb_pin16, 4)

# 需要修改的地方
wifiName = ""                   # wifi 名称，不支持5G wifi
wifiPassword = ""       # wifi 密码
#wifiName = ""
#wifiName = ""   # wifi 名称，不支持5G wifi
#wifiPassword = ""       # wifi 密码
# clientID = ""            # Client ID ，密钥，
myTopic1 = 'fengshan'                     # 需要订阅的主题值，
myTopic2 = 'shuibeng'
myTopic3 = 'fengmingqi'
myTopic4 = 'shuishen'
myTopic5 = 'light'
myTopic6 = 'shidu'
myTopic7 = 'yudi'
myTopic8 = 'turangshidu'

TOPIC_dict={}

MQTT_TOPIC = ""



# 默认设置
serverIP = ""    # mqtt 服务器地址
port = 1883
clientID = ""


# WIFI 连接函数
def do_connect():
    import network
    sta_if = network.WLAN(network.STA_IF)
    if not sta_if.isconnected():
        print('connecting to network...')
        sta_if.active(True)
        sta_if.connect(wifiName, wifiPassword)
        while not sta_if.isconnected():
            pass
    print('connect  WiFi ok')


# 接收消息，并处理
def MsgOK(topic, msg):          # 回调函数，用于收到消息
    print(("topic:",topic,"msg:", msg))            # 打印主题值和消息值
    if topic == myTopic1.encode():     # 判断是不是发给myTopic的消息
        if msg == b"ON":     # 当收到on
            print("fan is on")
            global fengshan_message
            fengshan_message = "ON"
            fengshan_pin1.value(0)
            fengshan_pin2.value(1)
        elif msg == b"OFF":              # 当收到off
            print("fan is off")
            global fengshan_message
            fengshan_message = "OFF"
            fengshan_pin1.value(0)
            fengshan_pin2.value(0)
    if topic == myTopic2.encode():     # 判断是不是发给myTopic的消息
        if msg == b"ON":     # 当收到on
            print("shuiebng is on")
            global shuibeng_message
            shuibeng_message = "ON"
            shuibeng_pin1.value(0)
            shuibeng_pin2.value(1)
        elif msg == b"OFF":              # 当收到off
            print("shuibeng is off")
            global shuibeng_message
            shuibeng_message = "OFF"
            shuibeng_pin1.value(0)
            shuibeng_pin2.value(0)
    if topic == myTopic3.encode():# 判断是不是发给myTopic的消息
        print("top3",msg)
        print(str(msg == b"ON"))
        if msg == b"ON":     # 当收到on
            print("fengmingqi is on")
            global beeper_message
            beeper_message = "ON"
        elif msg == b"OFF":              # 当收到off
            print("fengmingqi is off")
            global beeper_message
            beeper_message = "OFF"
    if topic == myTopic4.encode():# 判断是不是发给myTopic的消息
        print("top4",msg)               #通过订阅这种方式实现远程控制
        topic4=msg.decode()
        sub_number=int(topic4)
    # if topic == myTopic5.encode():# 判断是不是发给myTopic的消息
    #     print("top3",msg)
    #     print(str(msg == b"ON"))
    #     if msg == b"ON":     # 当收到on
    #         print("fengmingqi is on")
    #         global beeper_message
    #         beeper_message = "ON"
    #     elif msg == b"OFF":              # 当收到off
    #         print("fengmingqi is off")
    #         global beeper_message
    #         beeper_message = "OFF"
    # if topic == myTopic6.encode():# 判断是不是发给myTopic的消息
    #     print("top3",msg)
    #     print(str(msg == b"ON"))
    #     if msg == b"ON":     # 当收到on
    #         print("fengmingqi is on")
    #         global beeper_message
    #         beeper_message = "ON"
    #     elif msg == b"OFF":              # 当收到off
    #         print("fengmingqi is off")
    #         global beeper_message
    #         beeper_message = "OFF"
    # if topic == myTopic7.encode():# 判断是不是发给myTopic的消息
    #     print("top3",msg)
    #     print(str(msg == b"ON"))
    #     if msg == b"ON":     # 当收到on
    #         print("fengmingqi is on")
    #         global beeper_message
    #         beeper_message = "ON"
    #     elif msg == b"OFF":              # 当收到off
    #         print("fengmingqi is off")
    #         global beeper_message
    #         beeper_message = "OFF"
    # if topic == myTopic8.encode():# 判断是不是发给myTopic的消息
    #     print("top3",msg)
    #     print(str(msg == b"ON"))
    #     if msg == b"ON":     # 当收到on
    #         print("fengmingqi is on")
    #         global beeper_message
    #         beeper_message = "ON"
    #     elif msg == b"OFF":              # 当收到off
    #         print("fengmingqi is off")
    #         global beeper_message
    #         beeper_message = "OFF"

# 初始化mqtt连接配置
def connect_and_subscribe():
    client = MQTTClient(clientID, serverIP, port,user="", password="")
    client.set_callback(MsgOK)
    client.connect()
    client.subscribe(myTopic1)# 订阅主题和接收消息
    client.subscribe(myTopic2)
    client.subscribe(myTopic3)
    client.subscribe(myTopic4)
    print("Connected1 to %s" % serverIP)
    return client

def restart_and_reconnect():
    print('Failed to connect to MQTT broker. Reconnecting...')
    time.sleep(5)
    machine.reset()

# 开始连接WIFI
do_connect()

# 开始连接MQTT
try:
    client = connect_and_subscribe()
except OSError as e:

    restart_and_reconnect()


while True:
    try:
        print(Key.value())
        client.check_msg()
        dht.measure()
        #print("T:", dht.temperature())
        #print("H:", dht.humidity())
        data_shuiwen = {
            "services": [{
                "service_id": "all",
                "properties": {
                    "shuishen": water_sensor.read(),
                    "turangshidu": soil_sensor.read(),
                    "shidu": dht.humidity(),
                    "yudi": rain_sensor.read(),
                    "light": light_sensor.read(),
                    "shuibeng": shuibeng_message,
                    "fengshan": fengshan_message,
                    "fengmingqi": beeper_message,
                    "wendu": dht.temperature()

                }
            }
            ]
        }
        data_shuibengoff = {
            "services": [{
                "service_id": "all",
                "properties": {
                    "shuishen": water_sensor.read(),
                    "turangshidu": soil_sensor.read(),
                    "shidu": dht.humidity(),
                    "yudi": rain_sensor.read(),
                    "light": light_sensor.read(),
                    "shuibeng": shuibeng_message,
                    "fengshan": fengshan_message,
                    "fengmingqi": beeper_message,
                    "wendu": dht.temperature()

                }
            }
            ]
        }
        temp_ = str(dht.temperature())
        hum_ = str(dht.humidity())
        oled.text(0, 0, 'beeper:'+beeper_message)
        oled.text(0, 2, 'temp:'+temp_+"C")
        oled.text(60, 2, 'hum:'+hum_+"%")
        #oled.text(0,4, 'beeper:'+beeper_message)
        oled.text(0,4, 'shibeng:'+shuibeng_message)
        oled.text(0,6,"fengshan:"+fengshan_message)
        if Key.value() == 0:


            shuibeng_message = "ON"
            shuibeng_pin1.value(0)
            shuibeng_pin2.value(1)
            print("shuibeng_message ON")
            #client.publish(MQTT_TOPIC, json.dumps(data_shuiwen))
        if Key.value() ==1:
            #关闭状态 优先手动开关
            if water_sensor.read() > sub_number:


                shuibeng_message = "ON"
                beeper_message = "ON"
            else:


                shuibeng_message = "OFF"
                beeper_message = "OFF"
            #global shuibeng_message
            shuibeng_message = "OFF"
            print("shuibeng_message OFF")
            shuibeng_pin1.value(0)
            shuibeng_pin2.value(0)

        # if water_sensor.read()>sub_number:
        #     shuibeng_message = "ON"
        #     beeper_message ="ON"
        # else:
        #     shuibeng_message = "OFF"
        #     beeper_message ="OFF"

        if beeper_message == "OFF":
            beeper.duty(0)

        elif beeper_message == "ON":
            beeper.duty(1,frep=20)


        time.sleep(2)
        print(json.dumps(data_shuiwen))
        client.publish(MQTT_TOPIC, json.dumps(data_shuiwen))

    except OSError as e:  # 如果出错就重新启动
        print('Failed to connect to MQTT broker. Reconnecting...')
        restart_and_reconnect()

